package cola.rh.System.Controller;

import cola.rh.System.Entity.User;
import cola.rh.System.Entity.vo.LoginVo;
import cola.rh.System.Service.UserService;
import cola.rh.System.common.jwt.JwtHelper;
import cola.rh.System.common.result.Result;
import cola.rh.System.common.utils.MD5Util;
import cola.rh.System.exception.ColaException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Name: IndexController
 * @Author: Cola
 * @Time: 2023/3/9 22:23
 * @Description: IndexController
 */
@Api(tags = "主页管理")
@RestController
@Slf4j
@RequestMapping("/v1/api/index")
public class IndexController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @param loginVo loginVo
     * @return Result
     */
    @ApiOperation("登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo) {
        String username = loginVo.getUsername();
        User user = userService.getByUsername(username);
        if (null == user) {
            throw new ColaException(201, "用户不存在");
        }
        if (!MD5Util.encrypt(loginVo.getPassword()).equals(user.getPassword())) {
            throw new ColaException(201, "密码错误");
        }
        if (user.getStatus().intValue() == 0) {
            throw new ColaException(201, "账号被封禁");
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(user.getId(), user.getUsername()));
        return Result.ok(map);
    }

    /**
     * 获取用户登录信息
     *
     * @param request request
     * @return 用户登录信息
     */
    @GetMapping("info")
    public Result info(HttpServletRequest request) {
        /*获取请求头中的 token 并解析*/
        String username = JwtHelper.getUsername(request.getHeader("token"));
        /*根据用户名获取用户信息*/
        Map<String, Object> map = userService.getUserInfo(username);
        return Result.ok(map);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("logout")
    public Result logout() {
        return Result.ok();
    }
}
